package com.thti.mecool.client.model.biz;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;

import com.thti.mecool.client.db.DataBase;
import com.thti.mecool.client.model.po.MobileMessages;

public class MessagesBizImpl {
	private DataBase dataBase;

	public MessagesBizImpl(Context context) {
		dataBase = new DataBase(context);
	}
	
	public void save(MobileMessages mobileMessages){
		String sql="insert into messages(id,head,body,priority,type,createdOn,flag) values(?,?,?,?,?,?,?)";
		dataBase.execObject(sql, new Object[]{mobileMessages.getId(),mobileMessages.getHead(),mobileMessages.getBody()
				,mobileMessages.getPriority(),mobileMessages.getType(),mobileMessages.getCreatedOn(),mobileMessages.getFlag()});
		dataBase.close();
	}

	@SuppressWarnings("unchecked")
	public List<MobileMessages> findall(){
		String sql="select id,head,body,priority,type,createdOn from messages  order by createdOn desc";
		List<MobileMessages> list=new ArrayList<MobileMessages>();
		list=dataBase.findAll(MobileMessages.class, sql, new String[]{});
		dataBase.close();
		return list;
		
	}
	@SuppressWarnings("unchecked")
	public List<MobileMessages> findUngent(){
		String sql="select id,head,body,priority,type,createdOn from messages where priority=? and type=?";
		List<MobileMessages> list=new ArrayList<MobileMessages>();
		list=dataBase.findAll(MobileMessages.class, sql, new String[]{"URGENT","UNREAD"});
		dataBase.close();
		return list;
	}
	public boolean findAssign(){
		Cursor cursor=dataBase.getWritableDatabase().rawQuery("select createdOn from messages where priority='ASSIGN' AND flag=1 ORDER BY createdOn DESC LIMIT 0,1", new String[]{});
		int i=0;
		while(cursor.moveToNext()){
//			date=TimeUtil.dateToString(new Date(cursor.getLong(0)),2);
			i++;
		}
		cursor.close();
		dataBase.getWritableDatabase().close();
		return i>0?true:false;
	}
	public void upAssign(){
		String sql="update messages set flag=0 where priority='ASSIGN'";
		dataBase.execObject(sql, new String[]{});
		dataBase.close();
	}
	public void upUrgent(String id){
		String sql="update messages set type='READ' where priority='URGENT' and id=?";
		dataBase.execObject(sql, new String[]{id});
		dataBase.close();
	}
	@SuppressWarnings("unchecked")
	public List<MobileMessages> findUnReadAllMsg(){
		String sql="select * from messages where type=?";
		List<MobileMessages> list=new ArrayList<MobileMessages>();
		list=dataBase.findAll(MobileMessages.class, sql, new String[]{"UNREAD"});
		dataBase.close();
		return list;
	}
	
	public void delete(String Id){
		String sqlString="delete from messages where Id=?";
		dataBase.execObject(sqlString, new String[]{Id});
		dataBase.close();
	}
	
	public void update(String id){
		String sql="update messages set type='READ' where id=?";
		dataBase.execObject(sql, new Object[]{id});
		dataBase.close();
	}
}
